/**
 * @file glob.c
 * @author septem (jsm920@outlook.com)
 * @brief 见 glob.h
 * @version 0.1
 * @date 2025-02-13
 * 
 * @copyright Copyright (c) 2025
 * 
 */
#include "match.h"
#if defined(_WIN32) && defined(_MSC_VER)
// #pragma execution_character_set("utf-8")
#define WIN32_LEAN_AND_MEAN // 预处理器宏定义，它告诉编译器仅包含Windows SDK中最常用的函数和数据类型，从而减小编译时间和生成的可执行文件大小。
#include <stdio.h>
#include <stdlib.h> // malloc() realloc()
#elif defined(__linux__)
#include <stdio.h>
#endif

gmatch_t* GmatchInit(char* pattern)
{
    unsigned int _szMem = sizeof(gmatch_t) + 256;
    unsigned int _cntPGG = 8;
    gmatch_t* _pg = (gmatch_t*)malloc(_szMem);
    if(_pg == NULL || NULL == (_pg->pgg = (gmatchgrammar_t**)malloc( _cntPGG * sizeof(gmatchgrammar_t*))))
    {
        free(_pg);
        return NULL;
    }
    _pg->cnt = 0;
    // 分析 pattern
    unsigned int _posMem = sizeof(gmatch_t);// 当前正在使用的 pg 位置
    unsigned int _serPGG = 0; // 当前正在使用的 pg->pgg序号
    int i = 0; // 正在分析的 pattern 序号
    unsigned int _beg = -1;
    unsigned int _end = -1;
    while (pattern[i])
    {
        if(pattern[i] == '?')
        {
            _beg = i++;
            while (pattern[i] == '?') {i++;}
            i--;
            _end =  i;
            if(_serPGG>= _cntPGG)
            {
                gmatchgrammar_t** pggTmp = (gmatchgrammar_t**)realloc(_pg->pgg,( _cntPGG+8) * sizeof(gmatchgrammar_t*));
                if(pggTmp == NULL)
                {
                    free(_pg->pgg);free(_pg);return NULL;
                }
                _pg->pgg = pggTmp; _cntPGG += 8;
            }
            unsigned int szMemNeed = roundup(sizeof(gmatchgrammar_t), sizeof(void*)) ;
            if(_posMem+ szMemNeed >= _szMem)
            {
                unsigned int a =  _posMem+ szMemNeed - _szMem; a = (a >= 256 ? roundup(a, 256):256);
                gmatch_t* pgTmp = (gmatch_t*)realloc( _pg,_szMem + a);
                if(pgTmp == NULL)
                {
                    free(_pg->pgg);free(_pg);return NULL;
                }
                _pg = pgTmp; _szMem+=a;
            }
            _pg->pgg[_serPGG] = (gmatchgrammar_t*)((char*)_pg + _posMem);
            _posMem+=szMemNeed;
            _pg->pgg[_serPGG]->type = GMATCH_QUESTION;
            _pg->pgg[_serPGG]->d.question.cnt = _end-_beg+1;
        }
        i++;
    }
    
}
void GmatchUninit(gmatch_t* pg)
{
    if(pg) {free(pg);}
}
int Gmatch(gmatch_t* pg,char* path)
{
    
}

int Gmatch1(char* pattern,char* path)
{
    gmatch_t* pg = GmatchInit(pattern);
    if(pg)
    {
        int r = Gmatch(pg, path);
        GmatchUninit(pg);
        return r;
    }
    return -1;
}

int GmatchCopy(gmatch_t* src,gmatch_t* dst, unsigned int sz)
{

}